package com.congee02.scheduling;

import com.congee02.ThreadProvider;

/**
 * @author congee02
 * @date 2/1/2023 12:04 PM
 */
public class ThreadYieldTest {

    public static void main(String[] args) {
        ThreadProvider provider = new ThreadToYield();
        Thread t2 = provider.thread("T2");

        t2.start();
        for (int i = 0 ;; i ++ ) {
            try {
                Thread.sleep(1 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ": [YIELD] THREAD " + i);
            if (i == 10) {
                Thread.yield();
                System.out.println(Thread.currentThread().getName() + " 礼让，礼让可能失败");
            }
        }
    }
    
    private static class ThreadToYield implements ThreadProvider {

        @Override
        public void run() {
            System.out.println(this);
            for (int i = 0 ; i < 20 ; i ++ ) {
                try {
                    Thread.sleep(1 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ": [YIELD] THREAD " + i);
            }
        }
    }
}
